package Tree;

/**
 * @Classname JZ68二叉树的最近公共祖先
 * @Description TODO
 * @Date 2023/2/23 17:58
 * @Created by xjl
 */
public class JZ68二叉树的最近公共祖先 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    /**
     * @description 二叉树的最近公共祖先
     * @param: root
     * @param: p
     * @param: q
     * @date: 2023/2/23 17:58
     * @return: Tree.JZ68二叉树的最近公共祖先.TreeNode
     * @author: xjl
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root==null||root==p||root==q){
            return root;
        }
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if (left==null){
            return right;
        }
        if (right==null){
            return left;
        }
        return root;
    }
}
